<template>
  <div >
    <el-checkbox v-model="checkedAll" @change="handleCheckAllChange">全选/全不选</el-checkbox>

    <hot-table

      :id="templateType + `Id`"
      ref="hotTable"
      :data="templateData"
      :settings="hotSettings"
      class="margin-top text-sm"
    ></hot-table>
    <div v-loading.fullscreen.lock="fullscreenLoading"></div>
  </div>
</template>

<script>
import { clone } from "@/utils/clone";
import { parseTime } from "@/utils";
import { HotTable } from "@handsontable/vue";
import Handsontable from "handsontable";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import "handsontable/languages/zh-CN";
import "handsontable/dist/handsontable.full.css";
import globalData from "@/utils/config";

// import { log } from "console";
export default {
  components: {
    HotTable
  },
  props: {
    list: {
      type: Object,
      default: function() {
        return {};
      }
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    listData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    initOptionsData: {
      type: Object,
      default: function() {
        return {};
      }
    },
    templateName: {
      validator: function(value) {
        // 这个值必须匹配下列字符串中的一个
        return ["Receivable"].indexOf(value) !== -1;
      }
    },
    templateType: {
      type: String,
      default: "receivable"
    },
    templateOptUser: {
      type: String,
      default: ""
    },

    templateData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    oldData: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    receveToPay: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    payToReceve: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    templateDelReceveIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateDelPayIds: {
      type: Array,
      default: function(params) {
        return [];
      }
    },
    templateOptions: {
      type: Object,
      default: function(params) {
        return {};
      }
    }
  },
  data() {
    return {
      autoHeight: "auto",
      show: false,
      fullscreenLoading: false,
      showBychecked:true,
      headerList: [
        `序号`,
        "<span style='color:red;'>公司</span>",
        "<span style='color:red;'>费用名称</span>",
        "类型",
        "C类",
        "<span style='color:red;'>责任人</span>",
        "<span style='color:red;'>数量</span>",
        "<span style='color:red;'>单价</span>",
        "<span style='color:red;'>币种</span>",
        "总额",
        "余额",
        "<span style='color:red;'>账单类型</span>",

        "录入人",
        "修改人",
        "备注",
        "费用日期",
        // "销账日期",
        "创建日期",
        "操作"
      ],
      headerList2: [
        `序号`,
        "<span style='color:red;'>公司</span>",
        "<span style='color:red;'>费用名称</span>",
        "类型",
        "C类",
        "<span style='color:red;'>责任人</span>",
        "<span style='color:red;'>数量</span>",
        "<span style='color:red;'>单价</span>",
        "<span style='color:red;'>币种</span>",
        "总额",
        "余额",
        "<span style='color:red;'>账单类型</span>",
        "是否分配",
        "录入人",
        "修改人",
        "备注",
        "费用日期",
        // "销账日期",
        "创建日期",
        "操作"
      ],
      columns1: [
        {
          data: "selectStatus",
          width: 40,
          type: "checkbox"
        },
        {
          data: "serCusId", // 公司
          // width: 200,
          type: "autocomplete",
          // source: this.templateOptions.companyOptions
          source: async (query, process) => {
            console.log("query :>> ", query);
            const s = this.templateOptions.companyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            console.log("s :>> ", s);
            process(s);
          }
        },
        {
          data: "costName", // 费用名称
          // width: 80,
          type: "autocomplete",
          // source: this.templateOptions.configPayNameOptions
          source: async (query, process) => {
            const s = this.templateOptions.configPayNameOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "costNameType", // 类型
          // width: 80,
          readOnly: true,
          type: "text" //
        },
        {
          data: "configPayTypec", // C类
          type: "autocomplete",
          width: 40,
          source: this.templateOptions.paycOptions
        },
        {
          data: "responsibleId", // 责任人
          // width: 80,
          type: "autocomplete",

          source: async (query, process) => {
            const s = this.templateOptions.userOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "count", //数量
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "unitPrice", //单价
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();

            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }

            val = val.slice(0, val.indexOf("."));
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",

          source: async (query, process) => {
            const s = this.templateOptions.currencyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "totalCost", //总额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "remain", // 余额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "billType", //账单类型
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.options
        },

        {
          data: "inputUser", // 录入人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "lastOperator", //修改人
          readOnly: true,
          // width: 80,
          type: "text"
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        },

        {
          data: "accountDate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        // {
        //   data: "billingDate",
        //   width: 100,
        //   type: "date",
        //   renderer:()=>{

        //   }
        // },

        {
          data: "cdate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          readOnly: true,
          // width: 100,
          renderer: this.coverRenderer
        }
      ],
      //应付
      columns2: [
        {
          data: "selectStatus",
          width: 40,
          type: "checkbox"
        },
        {
          data: "serCusId", // 公司
          // width: 200,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.serviceOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "costName", // 费用名称
          // width: 80,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.configPayNameOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "costNameType", // 类型
          // width: 80,
          readOnly: true,
          type: "text" //
        },
        {
          data: "configPayTypec", // C类
          type: "autocomplete",
          width: 40,
          source: this.templateOptions.paycOptions
        },
        {
          data: "responsibleId", // 责任人
          width: 80,
          type: "autocomplete",
          source: async (query, process) => {
            const s = this.templateOptions.userOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "count", //数量
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();
            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }
            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "unitPrice", //单价
          // width: 60,
          type: "numeric",

          validator: function(value, callback) {
            let val = value.toString();

            if (val.indexOf("-") > -1) {
              val = val.slice(1);
            }

            val = val.slice(0, val.indexOf("."));

            if (val.length <= 5) {
              callback(true);
            } else {
              callback(false);
            }
          }
        },
        {
          data: "currency", // 币种
          // width: 60,
          type: "autocomplete",
          // source: this.templateOptions.currencyOptions
          source: async (query, process) => {
            const s = this.templateOptions.currencyOptions.filter(
              x => x && x.toLowerCase().indexOf(query.toLowerCase()) > -1
            );
            process(s);
          }
        },
        {
          data: "totalCost", //总额remain totalCost
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "remain", // 余额
          // width: 60,
          type: "numeric",
          readOnly: true,
          numericFormat: {
            pattern: "0.00"
          }
        },
        {
          data: "billType", //账单类型
          // width: 80,
          type: "autocomplete",
          source: this.templateOptions.options
        },
        {
          data: "isAllocated", // 是否分配
          // width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "inputUser", // 录入人
          // width: 80,
          readOnly: true,
          type: "text"
        },
        {
          data: "lastOperator", //修改人
          readOnly: true,
          // width: 80,
          type: "text"
        },
        {
          data: "remark", //备注
          // width: 200,
          type: "text"
        },

        {
          data: "accountDate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          data: "cdate",
          // width: 100,
          type: "date",
          dateFormat: "YYYY-MM-DD"
        },
        {
          readOnly: true,
          // width: 100,
          renderer: this.coverRenderer
        }
      ],
      changeList: [],
      checkedAll: false,
      props: [
        "serCusId",
        "costName",
        "responsibleId",
        "count",
        "unitPrice",
        "currency",
        "billType"
      ],
      rowIndex: 0,
      delId: ""
    };
  },
  computed: {
    hotSettings() {
      return {
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders:
          this.templateType === "receivable"
            ? this.headerList
            : this.headerList2,
        width: "100%",
        // height: this.autoHeight,
        height: 500,
        columns:
          this.templateType === "receivable" ? this.columns1 : this.columns2,
        tableClassName: [`table-${this.templateType}`],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        cells: this.rowReadonly,
        // className: ["cell-select"],
        // 单击之后
        // afterOnCellMouseDown: (event, coords, TD) => {

        //   if ((coords.row === -1, coords.col === 17)) {
        //   }
        // },
        beforeRemoveRow: async (index, amount, physicalRows, source) => {
          for (const i of physicalRows) {
            if (
              this.templateData[i].totalCost !== this.templateData[i].remain
            ) {
              this.$message.error("余额不等于总额，无法删除");
              return false;
            }
          }

          if (
            (this.templateType === "receivable" &&
              !this.verifyShow.deleteRece) ||
            (this.templateType === "payable" && !this.verifyShow.deletePay)
          ) {
            return false;
          }

          if (amount > 1) {
            this.$message.error("当前不支持删除多行");
            return false;
          }
          this.delId = this.templateData[physicalRows[0]].id
            ? this.templateData[physicalRows[0]].id
            : "";
          if (this.delId) {
            const data = await this.saveDel({ id: this.delId });
            console.log("data :>> ", data);
            if (!data) {
              return false;
            }
          }
          if (this.templateData.length === 1) {
            this.templateData.push({});
          }
        },
        beforeChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          console.log("changes: ", changes); // row, prop, oldVal, newVal
          console.log("source: ", source); // op
          if (source && "edit" == source) {
            const [row, prop, oldValue, newValue] = changes[0];

            // 判断余额 是否等于总额
            if (
              this.templateData[row].remain !==
                this.templateData[row].totalCost &&
              prop !== "selectStatus"
            ) {
              console.log("不可编辑 :>> ");
              this.$notify.error({
                position: "bottom-right",
                message: "更改失败，费用已销账"
              });
              changes.length = 0;
              return;
            }

            if (prop) {
              if (prop == "count" && oldValue != newValue) {
                // 修改数量
                if (this.templateData[row].unitPrice < 0 && newValue < 0) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }

                this.changeCount(row, newValue);
              } else if (prop == "unitPrice" && oldValue != newValue) {
                console.log("1111 :>> ", 1111);
                if (
                  this.verifyShow.saler &&
                  this.templateType === "receivable" &&
                  this.oldData.length > 0 &&
                  this.oldData[row] &&
                  this.oldData[row].costName === "运费" &&
                  this.templateData[row].costName === "运费" &&
                  newValue < this.oldData[row].unitPrice
                ) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "修改后的运费比原数据小"
                  });
                  changes.length = 0;
                  return;
                }
                console.log("222 :>> ", 222);
                // 修改单价
                if (
                  this.templateData[row].count < 0 &&
                  newValue < 0 &&
                  oldValue != newValue
                ) {
                  this.$notify.error({
                    position: "bottom-right",
                    message: "不能数量与单价两个都是负数"
                  });
                  changes.length = 0;
                  return;
                }
                this.changeUnitPrice(row, newValue);
              } else if (prop == "costName" && oldValue != newValue) {
                // 修改费用名称
                this.changePayName(row, newValue);
              } else if (prop == "configPayTypec" && oldValue != newValue) {
                // 判断是否可以修改C类
                if (this.templateData[row].costNameType !== "C") {
                  this.$notify({
                    type: "warning",
                    message: "仅仅当费用名称为C类的时候需要录入",
                    position: "bottom-right"
                  });
                  changes.length = 0;
                  return;
                }
              }
            }
          }
        },

        afterScrollHorizontally: () => {
          this.setDisabled();
        },
        afterScrollVertically: () => {
          this.setDisabled();
        },

        afterChange: async (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          // console.log("changes :>> ", changes);
          // 保存成功数据

          if (this.templateType !== "mergepayable") {
            this.setTdClass();
          }
          const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
            .children[0].children[0].children[2].children;
          if (
            td[row] &&
            td[row].children[0] &&
            td[row].children[0].children[0]
          ) {
            td[row].children[0].children[0].setAttribute("disabled", true);
          }
          if (!changes) return;
          console.log("changes :>> ", changes);
          const [row, prop, oldValue, newValue] = changes[0];
          if (prop == "selectStatus") {
              console.log('newValue->slect',newValue);
              if (newValue) {
                this.templateData[row].ynChoice = 1
              }else{
                this.templateData[row].ynChoice = 0
              }
              if (this.templateType !== "mergepayable") {
                console.log('newValue->chagne',row);
                setTimeout(async () => {
                  if (oldValue !== newValue) {
                   console.log('newValue->1111111111');

                    if (this.templateType === "receivable") {
                        // this.saveToReceivable(row, true);
                      this.saveWaybillReceiveOrPayYnChoice(row,0);
                      } else {
                        // this.saveToPayable(row, true);
                      this.saveWaybillReceiveOrPayYnChoice(row,1);
                      }
                  }

                });
              }
          }
          if (oldValue != newValue && prop !== "selectStatus") {
            // 修改人
            this.templateData[row].lastOperator = this.templateOptUser;

            const oldData = JSON.parse(
              sessionStorage.getItem(this.templateType)
            );

            const list =
              this.templateType === "receivable"
                ? this.columns1
                : this.columns2;
            const col = list.findIndex(x => x.data === prop);

            // 对比旧值
            if (
              (this.templateType !== "mergepayable" &&
                oldData[row] &&
                oldData[row][prop] !== this.templateData[row][prop]) ||
              !oldData[row]
            ) {
              await this.removeTdClass(row);
              const target = this.changeList.findIndex(
                x => x.row === row && x.col === 0
              );
              if (target > -1) {
                this.changeList.splice(target, 1);
              }

              this.changeList.push({
                row: row,
                col: 0,
                status: "change"
              });

              this.changeList.push({
                row: row,
                col: col,
                status: "change"
              });

              // console.log("修改必填数据 :>> ", this.changeList);

              this.setTdClass();
            }

            // 存在旧值，并且修改后的值 等于旧值
            if (
              this.templateType !== "mergepayable" &&
              oldData[row] &&
              oldData[row][prop] === this.templateData[row][prop]
            ) {
              await this.removeTdClass(row);
              this.templateData[row].lastOperator = this.templateOptUser;
              // 剔除坐标
              this.changeList.splice(
                this.changeList.indexOf(row + "," + col),
                1
              );
              for (const i in this.changeList) {
                if (this.changeList[i].row === row && this.changeList[i].col) {
                  this.changeList.splice(i, 1);
                }
              }
              this.setTdClass();
            }

            // sessionStorage.setItem("changeList", this.changeList);
          }
        },
        /**
         * [一个或多个cell被选中后触发(每选中一个触发一次)]
         * @param  {[number]} row              [开始cell的行索引]
         * @param  {[number]} column           [开始cell的列索引]
         * @param  {[number]} row2             [结束cell的行索引]
         * @param  {[number]} column2          [结束cell的列索引]
         * @param  {[object]} preventScrolling [Object with value property where its value change will be observed]
         * @param  {[number]} selectionLayerLevel [被选中的层级]
         */
        afterSelection: (
          row,
          prop,
          row2,
          prop2,
          preventScrolling,
          selectionLayerLevel
        ) => {
          if (this.templateType !== "mergepayable") {
            setTimeout(async () => {
              if (row !== this.rowIndex) {
                await this.checkRowInChange();
              }
              this.rowIndex = row;
            });
          }
        },
        /**
         * [当前单元格不被选中后触发]
         */
        afterDeselect: () => {
          if (this.templateType !== "mergepayable") {
            console.log("当前单元格不被选中后触发 :>> ", this.rowIndex);
            setTimeout(() => {
              this.checkRowInChange();
            });
          }
        },
        /**
         * [复制到表格后触发]
         * @param  {[array]} data   [复制的值]
         * @param  {[array]} coords [复制的目标区域坐标]
         */
        afterPaste: (data, coords) => {
          setTimeout(() => {
            console.log("this.templateData :>> ", this.templateData);
            for (const [i, e] of this.templateData.entries()) {
              if (
                (e.count || e.count === 0) &&
                (e.unitPrice || e.unitPrice === 0) &&
                !(e.count < 0 && e.unitPrice < 0)
              ) {
                this.changeCount(i, e.count);
              }
            }
          }, 500);
        },
        /**
         * [一行或者多行移除后触发]
         * @param  {[number]} index        [起始行的可视索引]
         * @param  {[number]} amount       [删除行的数量]
         * @param  {[array]}  physicalRows [被删除行的数据组成的数组]
         * @param  {[string]} source       [触发的源]
         */
        afterRemoveRow: (index, amount, physicalRows, source) => {}
      };
    }
  },
  watch: {
    templateData: {
      handler(val) {
        console.log("val :>> ", val);
        var length = this.templateData.length;
        // console.log("监控 所有的数据长度", length);
        for (let i = 0; i < this.templateData.length; i++) {
          if (this.templateData[i].ynChoice == 1) {
                this.templateData[i].selectStatus = true
              }else{
                this.templateData[i].selectStatus = false
              }
          if (
            this.templateType === "mergepayable" &&
            this.templateData[i].isAllocated === "1"
          ) {
            this.$delete(this.templateData[i], "isAllocated");
          }
        }
      },
      immediate: true,
      deep: true
    },
    oldData: {
      handler(val) {
        sessionStorage.setItem(this.templateType, JSON.stringify(this.oldData));
      },
      immediate: true
      // deep: true
    },
    verifyShow: {
      handler(val) {},
      immediate: true,
      deep: true
    }
  },
  mounted() {},
  methods: {
    handleCheckAllChange(){
      if (this.templateData && this.templateData.length>0) {
        console.log('this.handleCheckAllChange');
        console.log('this.templateType='+this.templateType)
        let updates = [];
        for (let i = 0; i < this.templateData.length; i++) {
             var rowUpdate = {};
              if (this.checkedAll) {
                    this.templateData[i].selectStatus = true
                    this.templateData[i].ynChoice == 1;
                  rowUpdate["ynChoice"] = 1;
                }else{
                    this.templateData[i].selectStatus = false
                    this.templateData[i].ynChoice == 0
                  rowUpdate["ynChoice"] = 0;
              }
              if(this.templateData[i].id){
                rowUpdate["id"] = this.templateData[i].id;
                updates.push(rowUpdate);
              }
          }
          if(updates.length > 0){
            let url = this.templateType == 'receivable' ? "saveWaybillReceiveYnChoice" : "saveWaybillPayYnChoice";
            ajax(url, updates).then(
              res => {
                if (res.code == 200) {
                  console.log("是否选择保存成功");
                  this.$refs.hotTable.hotInstance.render();
                }else{
                  if (null != res.message) {
                    this.$message.error(m(res.message));
                  } else {
                    this.$message.error("系统错误,保存失败!");
                  }
                }
              },
              error => {
                console.log(error);
              }
            );
          }else{
            this.$refs.hotTable.hotInstance.render();
          }

      }
    },
    setDisabled() {
      const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
        .children[0].children[0].children[2].children;
      // 禁止勾选
      for (const [i, e] of this.templateData.entries()) {
        if (e.disabled) {
          // [0].children[0].children;
          if (td[i] && td[i].children[0] && td[i].children[0].children[0]) {
            td[i].children[0].children[0].setAttribute("disabled", true);
          }
        }
      }
    },
    //行只读
    rowReadonly(row, col, prop) {
      var cellProperties = {};
      // 选择框禁选
      if (
        prop === "selectStatus" &&
        this.templateData[row] &&
        this.templateData[row].selectStatus &&
        this.templateData[row].disabled
      ) {
        this.setDisabled();

        cellProperties.readOnly = true;
      }

      if (this.templateType === "receivable" && !this.verifyShow.editRece) {
        cellProperties.readOnly = true;
      }
      if (this.templateType === "payable" && !this.verifyShow.editPay) {
        cellProperties.readOnly = true;
      }

      return cellProperties;
    },
    async setTdClass() {
      // console.log("this.changeList :>> ", this.changeList);

      for (const i of this.changeList) {
        if (
          // this.$refs.hotTable.$el.children[0] &&
          // this.$refs.hotTable.$el.children[0].children[0] &&
          // this.$refs.hotTable.$el.children[0].children[0].children[0] &&
          // this.$refs.hotTable.$el.children[0].children[0].children[0]
          //   .children[0] &&
          // this.$refs.hotTable.$el.children[0].children[0].children[0]
          //   .children[0].children[0] &&
          // this.$refs.hotTable.$el.children[0].children[0].children[0]
          //   .children[0].children[0].children[2] &&
          this.$refs.hotTable.$el.children[0].children[0].children[0]
            .children[0].children[0].children[2].children[i.row] &&
          this.$refs.hotTable.$el.children[0].children[0].children[0]
            .children[0].children[0].children[2].children[i.row].children[i.col]
        ) {
          const td = this.$refs.hotTable.$el.children[0].children[0].children[0]
            .children[0].children[0].children[2].children[i.row].children[
            i.col
          ];
          switch (i.status) {
            case "change":
              td.classList.add("bg-yellow");
              break;
            case "success":
              td.classList.add("bg-green");
              break;
            case "error":
              td.classList.add("bg-red");
              break;
          }
        }
      }
    },
    removeTdClass(row) {
      const elements = document
        .getElementsByClassName(`table-${this.templateType}`)[0]
        .querySelectorAll("td");

      Array.prototype.forEach.call(elements, function(element) {
        element.classList.remove("bg-yellow", "bg-green", "bg-red");
      });
    },
    checkRuleRow(i) {
      if (!i) {
        console.log('!i');
        return
      };
      if (!i.serCusId) {
        return false;
      } else if (!i.costName) {
        return false;
      } else if (i.costNameType === "C" && !i.configPayTypec) {
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        return false;
      } else if (i.count !== 0 && !i.count) {
        return false;
      } else if (!i.currency) {
        return false;
      } else if (i.unitPrice !== 0 && !i.unitPrice) {
        return false;
      } else if (!i.billType) {
        return false;
      }

      return true;
    },
    async checkRowInChange(type, row) {
      const index = row ? row : clone(this.rowIndex);

      if (!this.checkRuleRow(this.templateData[index])) return;

      const a = this.changeList.filter(i => i.row === index && i.col !== 0);

      if (a.length > 0 || type == "add") {
        console.log("执行保存 :>> ");

        if (this.templateType === "receivable") {
          this.saveToReceivable(index, type);
        } else {
          this.saveToPayable(index, type);
        }

        // saveToPayable saveToReceivable
      }
    },

    async saveRowInfo(row, code, message) {
      const list = clone(this.changeList);
      if (code === 200) {
        this.removeTdClass(row);
        for (let i = list.length - 1; i >= 0; i--) {
          if (list[i].row == row) {
            list.splice(i, 1);
          }
        }
        list.push({
          row: row,
          col: 0,
          status: "success"
        });
        // this.$emit("getInfo");
        this.$message.success("保存成功!");
        const data = clone(this.templateData);
        sessionStorage.setItem(this.templateType, JSON.stringify(data));
      } else {
        list.push({
          row: row,
          col: 0,
          status: "error"
        });
      }
      this.changeList = list;
      this.setTdClass();
    },
    changePayName(index, val) {
      var payType = this.templateOptions.payNameTypeMap[val];
      this.$set(this.templateData[index], "costNameType", payType);
    },
    changeCount(index, val) {
      const target = this.templateData[index];
      const totalCost = (target.unitPrice * 10000 * (val * 10000)) / 100000000;
      console.log("changeCount :>> ", totalCost);
      this.$delete(this.templateData[index], "totalCost");
      this.$delete(this.templateData[index], "remain");
      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },
    changeUnitPrice(index, val) {
      const target = this.templateData[index];
      const totalCost = (val * 10000 * (target.count * 10000)) / 100000000;
      console.log("changeUnitPrice :>> ", totalCost);
      this.$delete(this.templateData[index], "totalCost");
      this.$delete(this.templateData[index], "remain");
      this.$set(this.templateData[index], "totalCost", totalCost.toFixed(2));
      this.$set(this.templateData[index], "remain", totalCost.toFixed(2));
    },

    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = ``; // 清空单元格子集

      if (this.templateName === "Receivable") {
        let btnCopy = document.createElement("i");
        let btn2 = document.createElement("i");
        btnCopy.onclick = params => {
          this.onCopy(row);
        };
        btnCopy.setAttribute(
          "class",
          "el-icon-circle-plus-outline margin-right-sm text-green"
        );

        // btn.textContent = value ? value : "默认";

        if (this.templateType === "receivable" && this.verifyShow.createRece) {
          if (this.Constatvariable["status"] != 999) {
            td.appendChild(btnCopy); //添加按钮到单元格
          }
        } else if (
          (this.templateType === "payable" ||
            this.templateType === "mergepayable") &&
          this.verifyShow.createPay
        ) {
          td.appendChild(btnCopy); //添加按钮到单元格
        }

        if (
          this.templateData[row].totalCost === this.templateData[row].remain ||
          this.verifyShow.superAdmin
        ) {
          // 分配费用不能删除
          if (
            this.templateType === "payable" &&
            this.templateData[row].isAllocated == "是"
          ) {
            return;
          }
          let btnDel = document.createElement("i");

          btnDel.setAttribute(
            "class",
            "el-icon-remove-outline margin-right-sm text-red"
          );
          btnDel.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
          btnDel.onclick = params => {
            this.onDel(row);
          };
          if (
            this.templateType === "receivable" &&
            (this.verifyShow.deleteRece || this.verifyShow.superAdmin)
          ) {
            if (this.Constatvariable["status"] != 999) {
              td.appendChild(btnDel); //添加按钮到单元格
            }
          } else if (
            (this.templateType === "payable" ||
              this.templateType === "mergepayable") &&
            (this.verifyShow.deletePay || this.verifyShow.superAdmin)
          ) {
            td.appendChild(btnDel); //添加按钮到单元格
          }
        }

        if (
          this.templateType === "receivable" &&
          !this.verifyShow.seller &&
          this.verifyShow.editPay
        ) {
          let btnToPayable = document.createElement("i");

          btnToPayable.setAttribute(
            "class",
            "el-icon-bottom margin-right-sm text-blue"
          );
          btnToPayable.onclick = params => {
            this.copyToPayable(row);
          };
          td.appendChild(btnToPayable); //添加按钮到单元格
        } else if (
          this.templateType === "payable" &&
          !this.verifyShow.seller &&
          this.verifyShow.editRece
        ) {
          let btnToReceivable = document.createElement("i");

          btnToReceivable.setAttribute(
            "class",
            "el-icon-top margin-right-sm text-blue"
          );
          btnToReceivable.onclick = params => {
            this.copyToReceivable(row);
          };
          td.appendChild(btnToReceivable); //添加按钮到单元格
        }
      }

      const icon = document.createElement("i");
      icon.setAttribute("class", "el-icon-loading margin-left-sm text-blue ");
      icon.style = "display:none";
      td.appendChild(icon);

      return td;
    },
    removeChangList(data, row) {
      let arr = [];
      for (const i of data) {
        if (i.row > row) {
          i.row -= 1;
          arr.push({
            row: i.row - 1,
            col: i.col,
            status: i.status
          });
        } else if (i.row < row) {
          arr.push(i);
        }
      }
      this.changeList = arr;
      this.setTdClass();
    },
    async onDel(row) {
      if (this.templateData.length > 0) {
        const tData = clone(this.templateData);
        const data = this.templateData[row];
        console.log("this.templateType :>> ", this.templateType);
        if (this.templateType === "receivable") {
          if (data && null != data["id"] && "" != data["id"]) {
            this.fullscreenLoading = true;
            var delId = data["id"];
            //搞一下测试
            var param = {};
            console.log("当前的删除的应收数据Id", delId);
            param["id"] = delId;
            await this.saveDel(param, "receivable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台
            console.info("id 不存在 说明是在页面新加 不需要走后台");
            this.templateData.splice(row, 1);
            this.removeChangList(tData, row);
            const data = clone(this.templateData);
            sessionStorage.setItem(this.templateType, JSON.stringify(data));
          }
        } else if (this.templateType === "payable") {
          if (data && null != data["id"] && "" != data["id"]) {
            this.fullscreenLoading = true;
            var delId = data["id"];
            var param = {};
            console.log("当前的删除的应付数据Id", delId);
            param["id"] = delId;
            await this.saveDel(param, "payable", row);
          } else {
            //id 不存在 说明是在页面新加 不需要走后台
            this.templateData.splice(row, 1);
            this.removeChangList(tData, row);
            const data = clone(this.templateData);
            sessionStorage.setItem(this.templateType, JSON.stringify(data));
            console.info("id 不存在 说明是在页面新加 不需要走后台");
          }
        } else if (this.templateType === "mergepayable") {
          // 合单删除 需要点击保存按钮才删除
          this.templateData.splice(row, 1);
          this.$message.success("删除成功");
          if (data && null != data["id"] && "" != data["id"]) {
            var delId = data["id"];
            this.templateDelPayIds.push(delId);
          }
        }
      }
    },
    saveDel(param, type, row) {
      return new Promise((resolve, reject) => {
        const apiName =
          type === "receivable"
            ? "deleteWaybillReceiveById"
            : "deleteWaybillPayablesById";
        ajax(apiName, param)
          .then(res => {
            this.fullscreenLoading = false;
            if (res.code == 200) {
              // this.templateDelReceveIds.push(delId);

              this.$message.success("删除成功!");
              if (row) {
                this.templateData.splice(row, 1);
                this.removeChangList(tData, row);
              }

              const data = clone(this.templateData);
              sessionStorage.setItem(this.templateType, JSON.stringify(data));

              this.delId = "";
              resolve(true);
            } else {
              resolve(false);
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,删除失败!");
              }
            }
          })
          .catch(error => {
            console.log(error);
            reject();
          });
      });
    },
    onCopy(row) {
      // if (this.templateName === "Receivable") {
      const data = this.templateData[row];
      this.templateData.splice(row + 1, 0, {
        serCusId: data.serCusId,
        costName: data.costName,
        costNameType: data.costNameType,
        configPayTypec: "",
        responsibleId: data.responsibleId,
        inputUser: this.templateOptUser,
        lastOperator: "",
        unitPrice: data.unitPrice,
        count: data.count,
        currency: data.currency,
        totalCost: data.totalCost,
        remain: data.totalCost,
        billType: data.billType,
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        cdate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      });
      if (this.templateType !== "mergepayable") {
        this.checkRowInChange("add", row + 1);
      }

      // }
    },
    copyToPayable(row) {
      this.$confirm("确认复制到应付？")
        .then(_ => {
          console.log(this.templateData[row]);
          var target = clone(this.templateData[row]);
          console.log("------------------------");
          if (this.checkRule(target)) {
            target.id = null;
            target.remark = "";
            // target.remark =
            //   "于" +
            //   parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}") +
            //   this.templateOptUser +
            //   "复制应收而来";
            target.serCusId = null;
            //清关服务商
            let customsClearanceAgent = this.Constatvariable.customsClearanceAgent;
            if (customsClearanceAgent) {
              let serviceCompanyMap = this.initOptionsData["serviceCompanyMap"];
              let serviceCompanyName = serviceCompanyMap[customsClearanceAgent];
              target.serCusId = serviceCompanyName;
            }
            this.receveToPay.push(target);

          }
        })
        .catch(_ => {});
    },

    saveToPayable(row, type) {
      // this.$confirm("确认保存应付？")
      //   .then(_ => {

      console.log(this.templateData[row]);
      var target = this.templateData[row];
      target["waybillId"] = this.$route.query.waybillId;
      console.log("------------------------");
      if (this.checkRule(target)) {
        let td = null;
        if (!type) {
          const length =
            this.templateType === "receivable"
              ? this.columns1.length - 1
              : this.columns2.length - 1;
          if (
            // this.$refs.hotTable.$el.children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0].children[0].children[2] &&
            this.$refs.hotTable.$el.children[0].children[0].children[0]
              .children[0].children[0].children[2].children[row] &&
            this.$refs.hotTable.$el.children[0].children[0].children[0]
              .children[0].children[0].children[2].children[row].children[
              length
            ]
          ) {
            td = this.$refs.hotTable.$el.children[0].children[0].children[0].children[0].children[0].children[2].children[
              row
            ].children[length].getElementsByClassName("el-icon-loading")[0];
            console.log("td :>> ", td);
            td.style = "display:black";
          }
        }

        var list = [];
        list.push(target);
        let attrs = [];
        attrs["headers"] = {
          "YG-UNIQUE-KEY": target.onlyKey
        };
        console.log("attrs: ", attrs);
        ajax("saveWaybillPayablesBaseInfo", list)
          .then(res => {
            // this.showLoadIcon = false;
            if (!type && td) {
              td.style = "display:none";
            }
            if (res.code == 200) {
              target.lastOperator = "";
              target.inputUser = this.templateOptUser;
              target.accountDate = target.cdate = parseTime(
                new Date().toLocaleDateString(),
                "{y}-{m}-{d}"
              );
              if (target.id == null || target.id == "") {
                target.id = res.data;
              }
              console.log("target :>> ", target);
              this.saveRowInfo(row, res.code);
            } else {
              this.saveRowInfo(row, res.code, res.message);
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,保存失败!");
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      }

      // })
      // .catch(_ => {});
    },
    saveWaybillReceiveOrPayYnChoice(row, receiveOrpay) {
      var target = this.templateData[row];
      // console.log(target);
      var id = target.id;
      if(!id){
        return;
      }
      var ynChoice = target.ynChoice;
      if(!ynChoice){
        ynChoice = 0;
      }
      let updateRow = {"id":id,"ynChoice":ynChoice};
      var list = [];
      list.push(updateRow);
      console.log(list);
      let url = receiveOrpay == 1 ? "saveWaybillPayYnChoice" : "saveWaybillReceiveYnChoice";
      ajax(url, list).then(
        res => {
          if (res.code == 200) {
            console.log("是否选择保存成功")
          }else{
            if (null != res.message) {
              this.$message.error(m(res.message));
            } else {
              this.$message.error("系统错误,保存失败!");
            }
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    saveToReceivable(row, type) {
      // this.$confirm("确认保存应收？")
      //   .then(_ => {

      var target = this.templateData[row];
      target["waybillId"] = this.$route.query.waybillId;
      if (this.checkRule(target)) {
        let td = null;

        if (!type) {
          const length =
            this.templateType === "receivable"
              ? this.columns1.length - 1
              : this.columns2.length - 1;

          if (
            // this.$refs.hotTable.$el.children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0].children[0] &&
            // this.$refs.hotTable.$el.children[0].children[0].children[0]
            //   .children[0].children[0].children[2] &&
            this.$refs.hotTable.$el.children[0].children[0].children[0]
              .children[0].children[0].children[2].children[row] &&
            this.$refs.hotTable.$el.children[0].children[0].children[0]
              .children[0].children[0].children[2].children[row].children[
              length
            ]
          ) {
            td = this.$refs.hotTable.$el.children[0].children[0].children[0].children[0].children[0].children[2].children[
              row
            ].children[length].getElementsByClassName("el-icon-loading")[0];
            console.log("td :>> ", td);
            td.style = "display:black";
          }
          console.log("td :>> ", td);
        }
        var list = [];
        list.push(target);

        let attrs = [];
        attrs["headers"] = {
          "YG-UNIQUE-KEY": target.onlyKey
        };
        // if (target.id) {
        //   console.log(`有id，是编辑`);
        // } else {
        //   console.log(`没有id，是新增`);
        // }
        ajax("saveWaybillReceiveBaseInfo", list).then(
          res => {
            if (!type && td) {
              td.style = "display:none";
            }
            if (res.code == 200) {
              // target.lastOperator = "";
              // target.inputUser = this.templateOptUser;
              // target.accountDate = target.cdate = parseTime(
              //   new Date().toLocaleDateString(),
              //   "{y}-{m}-{d}"
              // );
              if (target.id == null || target.id == "") {
                target.id = res.data;
              }
              this.saveRowInfo(row, res.code);
            } else {
              this.saveRowInfo(row, res.code, res.message);
              if (null != res.message) {
                this.$message.error(m(res.message));
              } else {
                this.$message.error("系统错误,保存失败!");
              }
            }
          },
          error => {
            console.log(error);
          }
        );
      }

      // })
      // .catch(_ => {});
    },

    copyToReceivable(row) {
      this.$confirm("确认复制到应收？")
        .then(_ => {
          var target = clone(this.templateData[row]);

          if (this.checkRule(target)) {
            target.remark = "";
            // target.remark =
            //   "于" +
            //   parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}") +
            //   this.templateOptUser +
            //   "复制应付而来";
            target.serCusId = null;
            target.id = null;
            this.payToReceve.push(target);
            this.$message.error("已复制 请选择公司并保存 否则复制无效!");
          }
        })
        .catch(_ => {});
    },
    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        this.$message.error("请填写责任人");
        return false;
      } else if (i.count !== 0 && !i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (i.unitPrice !== 0 && !i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      } else if (
        i.totalCost &&
        (i.count || i.count == 0) &&
        (i.unitPrice || i.unitPrice == 0)
      ) {
        const total = (i.count * 10000 * (i.unitPrice * 10000)) / 100000000;
        console.log("i.totalCost :>> ", i.totalCost);
        console.log("total :>> ", total);
        console.log("total :>> ", total.toFixed(2));
        if (i.totalCost != total.toFixed(2)) {
          this.$message.error("总额不等于单价*数量，请检查");
          return false;
        }
      }
      return true;
    }
  }
};
</script>

<style></style>
